package com.eqdd.yiqidian.box.span.MovementMethod;

import android.text.Layout;
import android.text.Selection;
import android.text.Spannable;
import android.text.method.BaseMovementMethod;
import android.text.method.MovementMethod;
import android.view.MotionEvent;
import android.widget.TextView;

import com.eqdd.yiqidian.box.span.TagSpan;

/**
 * @author吕志豪 .
 * @date 18-3-2  下午2:05.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class ClickMovementMethod extends BaseMovementMethod {
    @Override
    public boolean onTouchEvent(TextView widget, Spannable buffer,
                                MotionEvent event) {
        int action = event.getAction();

        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(y);
            TagSpan[] links = buffer.getSpans(0, buffer.length(), TagSpan.class);

            if (links.length != 0) {
                if (action == MotionEvent.ACTION_UP) {
                    if (x < layout.getLineWidth(line)) {
                        for (int i = 0; i < line; i++) {
                            x += layout.getLineWidth(i);
                        }
                        int num = 0;
                        for (TagSpan link : links) {
                            if (x >= num && x < num + link.getSize()) {
                                link.onClick(widget);
                                break;
                            }
                            num += link.getSize();
                        }
                    }
                } else if (action == MotionEvent.ACTION_DOWN) {
                    Selection.setSelection(buffer,
                            buffer.getSpanStart(links[0]),
                            buffer.getSpanEnd(links[0]));
                }
                return true;
            } else {
                Selection.removeSelection(buffer);
            }
        }

        return super.onTouchEvent(widget, buffer, event);
    }



    public static MovementMethod getInstance() {
        if (sInstance == null)
            sInstance = new ClickMovementMethod();

        return sInstance;
    }

    private static ClickMovementMethod sInstance;
}
